<template>
	<div id="newActivity">
		<div class="content-box">
			<div v-loading="loadingChoose" element-loading-text="拼命加载中"> 
				<div v-show="$store.state.oneself.tplName.length!=0">
					<div class="filter-wrap">
						<div class="filter-box">
							<!--<div class="filter-item clearfix">
								<div class="filter-item-left">活动目标:</div>
								<div class="filter-item-right clearfix"><span  class="active" >全部</span><span>拉新</span><span>活跃</span></div>
							</div>-->
							<div class="filter-item clearfix">
								<div class="filter-item-left">分类模板:</div> 
								<div class="filter-item-right clearfix">
								
									<span :class="{'active':activeTbsSpan==index}" v-for="(item,index) in $store.state.oneself.tplName" :key="index" @click="modelSelect(item,index)">{{item.model_name}}</span> 
								</div>
								
							</div>
							<div class="up-btn text-right">
								<el-button  type="primary" class="btn" v-show="this.$route.name=='theirOwn'" @click="ImportCodeShow=true">上传模板</el-button>
							</div>
							<!--<div class="filter-item clearfix">
								<div class="filter-item-left"></div>
								<div class="filter-item-right clearfix"><button>节日活动</button><button>新玩法</button><span class="more-play">更多玩法</span></div>
							</div>-->
						</div>
					</div>
					<div class="template-container">
					
						<ul class="clearfix tpl-ul"  >
							<li v-for="(list,index) in $store.state.oneself.tableData" :key="index">
								<div class="active-list-box">
									<div class="template-content">
										<p>{{list.name}}</p>
										<div class="template-active-img" @mouseenter="qrcodeEvent($event,list)" >
											<img  v-lazy="ImgUrl+list.thumb">
											<div class="template-qrcode">
												<p>扫一扫预览</p>
												<div class="code-box">
													<div class="qrcode text-center"></div>
												</div>
												<span @click="useTemplate(list)">使用</span>
												<!--<span class="down-load" @click="download(list)">下载</span>-->
											</div>
										</div>
										<div class="new-icon"></div>
									</div>
								</div>
							</li>
						</ul>
					</div>
				</div>
				<div class="text-hit" v-show="$store.state.oneself.tplAll.length==0">{{errorText}}</div>
			</div>
			<div class="page-footer text-center" >
                <el-pagination
                    small
                    layout="prev, pager, next"
                    :total="total"
					:page-size="limit"
                    @current-change="pageChange"
                    >
                </el-pagination>
            </div>
		</div>

		
		<!--导入模板-->
        <el-dialog
            title="导入模板" 
            :visible.sync="ImportCodeShow"
            size="small"
            :show-close="!ImportCodeShow"
            :close-on-click-modal="!ImportCodeShow"
             >
             <div class="group-box" v-loading="ImportCodeLoading">
			 	<div class="group-modal">
					<span class="item-title">模板类型：</span>
					<div class="item-input">
						<el-select class="form-input" v-model="form.model_id" placeholder="请选择"> 	
							<el-option
							v-for="item in optionList"
							:key="item.id"
							:label="item.name"
							:value="item.id">
							</el-option>
						</el-select>
					</div>
				</div>
				<div class="group-modal">
					<span class="item-title">模板名称：</span>	
					<div class="item-input">
						<el-input  class="form-input" v-model="form.name" placeholder="模板名称"></el-input> 
					</div>
				</div>
				<div class="group-modal">
					<span class="item-title">模板文件名：</span>	
					<div class="item-input">
						<el-input  class="form-input" v-model="form.template" placeholder="模板文件名"></el-input> 
					</div>
				</div>
				<div class="group-modal">
					<span class="item-title">首页路径 ：</span>	
					<div class="item-input">
						<el-input  class="form-input" v-model="form.url" placeholder="如：文件名/index.html"></el-input> 
					</div>
				</div>
				<div class="group-modal">
					<span class="item-title">封面图路径 ：</span>	
					<div class="item-input">
						<el-input  class="form-input" v-model="form.thumb" placeholder="如：文件名/images/alasd.png"></el-input> 
					</div>
					<p style="font-size:12px;margin-left:110px;">支持640*1200像素，PNG、JPG格式，小于200KB</p>
				</div>
				<!--<div class="group-modal">
					<span class="item-title">模板首页：</span>	
					<div style="display:inline-block; vertical-align: middle;">
						<div class="upload-img-list">
							<p  v-show="!form.homeBg" @click="clickUpAttr(1)" >
								<input type="file" 
							       @change='addImgEvent'
							       accept="image/png, image/jpeg, image/jpg">
							</p>
							<p v-show="form.homeBg" class="p_img">
								<img :src="form.homeBg" />
								<i class="fa fa-times" 
								aria-hidden="true"
								v-show="form.homeBg"  @click="cancelBanner(1)"></i>
							</p>
						</div>
						<p style="font-size:12px;">支持640*1200像素，PNG、JPG格式，小于200KB</p>
					</div>
				</div>
				<div class="group-modal">
					<span class="item-title">模板封面：</span>	
					<div style="display:inline-block; vertical-align: middle;">
						<div class="upload-img-list" >
							<p  v-show="!form.imageUrl" @click="clickUpAttr(2)">
								<input type="file" 
							       @change='addImgEvent'
							       accept="image/png, image/jpeg, image/jpg">
							</p>
							<p v-show="form.imageUrl" class="p_img">
								<img :src="form.imageUrl" />
								<i class="fa fa-times" 
								aria-hidden="true"
								v-show="form.imageUrl" @click="cancelBanner(2)"></i>
							</p>
						</div>
						<p style="font-size:12px;">支持640*1200像素，PNG、JPG格式，小于200KB</p>
					</div>
				</div>-->
				<div class="group-modal">
					<span class="item-title">模板压缩包：</span>	
					<div class="item-input">
						<el-input class="element-input" disabled placeholder="请导入模板" v-model="form.tplZip">
							<label id="file" slot="append" class="file-label cursor">
								<input type="file" name="file" @change='addCouponCode' ref="couponFile" class="up-file-input"/> 
								<el-button >选择模板</el-button>
							</label> 
						</el-input> 
					</div> 
				</div>
                <div class="dialog-footer text-right">
                    <el-button @click="ImportCodeShow = false">取 消</el-button>
                    <el-button type="primary" @click="upLoadModel">导入</el-button>
                </div>
             </div>
            
        </el-dialog>

	</div>
</template>
<script>
import { baseImgPath } from './../../config/env'
import * as api from './../../api/api';
 import {mapGetters} from 'vuex';
 import QRCode from 'qrcodejs2'
	export default {
		data(){
			return {
				ImgUrl:baseImgPath,
				activeTbsSpan:0,//分类模板
				modulesClassShow:'', //当前选择的模板
				loadingChoose:false,	
				errorText:'暂无活动',
				qrcodeItem:null,
				//分页
				current_page:1, //当前页码
                last_page:'',//最后一页
                limit:8, //一页显示多少条
                total:0, //总条数

				//导入模板
				optionList: [],
                ImportCodeLoading:false,
                ImportCodeShow:false,
                
                uploadInput:'',  
                ImportPrizeId:'',

				form:{
					model_id:'',
					name:'',
					template:'',
					url:'',
					thumb:'', 
					tplZip:'',   //显示的导入模板
				},
				tplUrl:'', 
				clickUpLoadImg:null, //当前点击的upload
			}
		},
		methods: {
			qrcodeEvent (e,item) {
				let vm =this;
				let eventId=e.target.children[1].children[1].children[0];
				if(eventId.children.length==0){
					vm.qrcodeItem = new QRCode(eventId, {  
						width: 150,  // 设置宽度 
						height: 150, // 设置高度
						text: vm.ImgUrl+item.act_try_url
					}) 
				}	
            },
			//下载模板
			download(item){
				console.log(item);
			},
			useTemplate(item){
				if(item.model.type==0){
					//item.id 模板id;
					//item.model_id 模型id
					
					
					if(item.template=='vote-screen'){  //投票
						// this.$router.push({name:'surveyTpl',query:{surveyTplId:'web/modelRule?template_id=ab289cb2-f6e2-41e1-9f92-a40d3e734bc3'}});	
					}else if(item.template=='default'){//报名
						// this.$router.push({name:'surveyTpl',query:{surveyTplId:'web/modelRule?template_id=4c94192d-759b-4eb1-9ce6-ff965d289d52'}});	
					}else if(item.template=="prize-code"){ //口令
						this.$router.push({name:'setTemplate_code',query:{'tplModelId':item.id,'background':item.thumb,'bannerImg':item.banner_img,'model_id':item.model_id}});
					}else{
						this.$router.push({name:'commonTpl',query:{'tplModelId':item.id,'background':item.thumb,'bannerImg':item.banner_img,'model_id':item.model_id}});
					}
					
					// console.log(item);
				}
			},
			//选择分类模板
			modelSelect(item,index){
				let vm = this;
				vm.activeTbsSpan=index;
				vm.$store.state.oneself.modelIdIndex=index;
				vm.modulesClassShow=item.model_id;
				vm.$store.state.oneself.tplList.forEach((list,index)=>{
					if(list.model_id==item.model_id){
						let arr=[];
						list.tpls.forEach((a,b)=>{
							if(a.type==0||a.template=='prize-code'){
								arr.push(a);
							}
						});
						vm.$store.state.oneself.tplAll=arr;
						// vm.$store.state.oneself.tplAll=list.tpls;
						vm.pagination(1,vm.$store.state.oneself.tplAll);
					}
				})
			},
			fetchPrdList(){
				let vm = this;
				vm.loadingChoose=true;
				api.fetchActivityList({private:1}).then(res=>{
					vm.loadingChoose=false;
					vm.$store.state.oneself.tplName=res.data.data.mts;
					let arr=[];
					res.data.data.mts[0].tpls.forEach((item,index)=>{
						if(item.type==0||item.template=='prize-code'){
							arr.push(item);
						}
					});
					vm.$store.state.oneself.tplAll=arr;
					vm.pagination(1,vm.$store.state.oneself.tplAll);
					vm.total=res.data.data.mts[0].tpls.length;
					vm.$store.state.oneself.tplList=res.data.data.mts;
					// vm.errorText=''
				})
			},

			eventMouseenter(e,item){
				console.log(e);
				console.log(item);
			},
			//点击当前的页数
            pageChange(a){
                this.current_page=a;
				this.pagination(a,this.$store.state.oneself.tplAll);
            },
			//分页效果
			pagination(index,data){
				let vm = this;
				vm.total=data.length;
				vm.loadingChoose=true;
				vm.$store.state.oneself.tableData=[];
				setTimeout(function(){
					vm.loadingChoose=false;
					vm.$store.state.oneself.tableData = data.slice((index-1)*vm.limit,(index-1)*vm.limit+vm.limit);
				},400);
			},



			allPrdList(){
				let vm = this; 
				api.fetchActivityList({}).then(res=>{ 
					vm.optionList=res.data.data.mts[0].tpls; 
				})
			},
			 //选择
            addCouponCode(e){
                let vm = this; 
                let ext=e.target.value.toLowerCase().split('.').splice(-1); 
				let targetName=e.target.files[0].name; 
				if(ext[0]=='zip'){
					vm.ImportCodeLoading=true;
					let form = new FormData();  
					form.append('activity', e.target.files[0]); 
					api.templateUpload(form).then(res=>{
						this.ImportCodeLoading=false; 
						if(res.data.code==200){ 
							vm.tplUrl=res.data.data;
							vm.form.tplZip=targetName; 
							vm.$message({ message: '上传成功', type: 'success' });
						}else{
							vm.$message({ message: res.data.message });
						}
					});	
					e.target.value='';
				}else{
					vm.$message({ message: '请上传zip格式压缩包'});
				} 
            },
            //确认导入
            upLoadModel(){
                let vm = this;  
                if(vm.regUpload()){
					let body={
						model_id:vm.form.model_id,
						name:vm.form.name,
						template:vm.form.template,
						url:vm.tplUrl+'/act/'+vm.form.url,
						thumb:vm.tplUrl+'/act/'+vm.form.thumb, 
					};
					vm.ImportCodeLoading=true;
				   api.templateAdd(body).then(res=>{ 
					   vm.ImportCodeLoading=false;
					   if(res.data.code==0||res.data.code==200){
						   	vm.ImportCodeShow = false;
							vm.allPrdList();
					   }
				   });
                }  
            },
			//
			regUpload(){
				let vm = this;  
                if(vm.form.model_id==''){
                    vm.$message({ message: '请选择模板类型'}); 
					return false;
                }else if(vm.form.name==''){
                    vm.$message({ message: '请输入模板名称'}); 
					return false;
                }else if(vm.form.template==''){
                    vm.$message({ message: '请输入模板文件名'}); 
					return false; 
                }else if(vm.form.url==''){
                    vm.$message({ message: '请输入活动首页路径'});  
					return false;
                }else if(vm.form.thumb==''){
                    vm.$message({ message: '请输入封面图路径'});  
					return false;
                }else if(vm.form.tplZip==''){
					vm.$message({ message: '请上传模板压缩包'});  
					return false;	
				}else{
					return true;
				}
			},	


			// //删除选择的图片
			// cancelBanner(value){
			// 	if (value === 1) {
			// 		this.form.homeBg = '';
			// 	}else{
			// 		this.form.imageUrl = '';
			// 	}
			// },
			// clickUpAttr(val){
			// 	this.clickUpLoadImg=val;
			// },
			// //上传图片
			// addImgEvent(event){
			// 	var vm = this;
			// 	vm.ImportCodeLoading=true;
	        //     var img1 = event.target.files[0];
			// 	//生成临时图片路径
            //     var temSrc = URL.createObjectURL(img1);
	        //     var size = img1.size/1024;
			// 	if(size>200){
			// 		vm.ImportCodeLoading=false;
			// 		vm.$message({
			// 		showClose: true,
			// 		type: 'error',
			// 		message: '图片大小不能大于200KB'
			// 		}); 
			// 		return false;  
			// 	}
			// 	var _img = new Image();
        	// 	_img.onload = function  () { 
        	// 		var imgWidth = _img.width,
        	// 			imgHeight = _img.height; 
			// 		if (imgWidth!=640 || imgHeight!=1200) {
			// 			vm.ImportCodeLoading=false;
			// 			vm.$message({
			// 				showClose: true,
			// 				type: 'error',
			// 				message: '请上传尺寸为640*1200的图片'
			// 			}); 
			// 			return false;
			// 		};
					
			// 		let formdata = new FormData();
			// 		formdata.append('upfile', img1);
        	// 		if (vm.clickUpLoadImg ==1) {  
			// 	        api.uploadPrizeImg(formdata).then(res => {
			// 				vm.$message({
			// 					message: '上传成功',
			// 					type: 'success'
			// 				}); 
			// 				vm.ImportCodeLoading=false;
			// 	        	vm.form.homeBg = res.data.result;
			// 	        }).catch(err=>{
			// 				vm.httpStatusCode(err); 
			// 				vm.ImportCodeLoading=false;
			// 			})  
        	// 		}else{  
			// 	        api.uploadPrizeImg(formdata).then(res => {
			// 				vm.$message({
			// 					message: '上传成功',
			// 					type: 'success'
			// 				}); 
			// 				vm.ImportCodeLoading=false;
			// 	        	vm.form.imageUrl = res.data.result;
			// 	        }).catch(err=>{
			// 				vm.httpStatusCode(err); 
			// 				vm.ImportCodeLoading=false;
			// 			}) 
			// 		} 
			// 		setTimeout(function  () {
			//         	URL.revokeObjectURL(temSrc);
			//         },100);
			// 	}
			// 	_img.src = temSrc;
			// }

		},
		mounted(){
			//选择分类模板
			if(this.$store.state.oneself.tplAll.length==0){
				this.fetchPrdList();
			}else{
				this.activeTbsSpan=this.$store.state.oneself.modelIdIndex;
				this.pagination(1,this.$store.state.oneself.tplAll);
			}
			this.allPrdList();
		},
		components:{
			QRCode
		}
	}
</script>
<style lang="less" scoped>
	@import './../../style/chooseTemplate';
	.page-footer{
        width:100%;
        height: 87px;
        box-sizing: border-box;
        padding: 30px;
        background: #ffffff;
    }
	.up-btn{ 
		margin-top:10px;
		margin-right:10px;
	}
    .file-label{
        display: inline-block;
        // height:30px;
        // width:88px;
        padding: 10px 0;
        position: relative;
    }
    .up-file-input{
        cursor: pointer;
        display: block;
        opacity: 0;
        width:100%;
        height: 100%;
        position: absolute;
        top:0;
        left:0;
    }
    .push-text{
        color:#FB404B;
    }
	.group-box{
		padding:0 8%;
		.group-modal{
			margin:10px 0;
			.item-title{
				display:inline-block;
				width:100px;
				
			}
			.item-input{
				display:inline-block;
				.form-input{
					width:300px;
				}
			}
			.add-banner-btn{
				width: 60px;
				height: 60px;
				line-height: 52px;
				font-size: 30px;
				font-weight: 100;
				color: #888;
				border-color: #efefef;
				border: 1px solid #efefef;
				display: inline-block;
				text-align: center;
				background-color: #f4f8fb;
				cursor:pointer;
			}
			.fa-times{
				position: relative;
				top: -30px;
				font-size: 14px;
				color:#888888;
				cursor: pointer;
			}
			.fa-times:hover{
				opacity: 0.8;
			}
		}
	}

.upload-img-list p{
	width:100px;
	height: 100px;
	line-height: 98px;
	border: 1px solid #eeeeee;
	margin: 0 10px 20px;
	text-align: center;
	font-size: 30px;
	color: #aaaaaa;
}
.upload-img-list p:first-child{
	position: relative;
}
.upload-img-list p:first-child:before{
	content:'+';
}
.upload-img-list p input{
	cursor: pointer;
	display: block;
	opacity: 0;
	width:100%;
	height: 100%;
	position: absolute;
	top:0;
	left:0;
}
.upload-img-list p:not(:first-child){
	-webkit-background-size: contain;
	background-size: contain;
	background-position: center center;
	background-repeat: no-repeat;
}
.upload-img-list .p_img{
	position:relative;
	border:none;
	width:56px;
}
.upload-img-list p img{
	width:100%;
	height: 100%;
}
.upload-img-list .p_img .fa-times{
	position: absolute;
	top: -5px !important;
	right:-5px;
	font-size: 18px;
	color:#888888;
	cursor: pointer;
}
.upload-img-list .p_img .fa-times:hover{
	opacity: 0.8;
}
</style>